// releasePage/pages/addPictures/addPictures.js
import throttle from '../../../utils/throttle.js';
const app = getApp();

Page({
    /**
     * 页面的初始数据
     */
    data: {
        scrollViewHeight: '',
        // 从不同位置进入，00(我的)/01（城市秘书团）/02（测试点
        fromWhere: '',
        // 测试点/线id
        pointId: '',
        // 测试点/线类型
        pointType: '',
        // 图片墙前缀
        prefix: '',
        //上传照片
        sceneImageArr: [],
        // 图片描述
        description: [],
        // 当前描述索引
        currentDesIndex: 0,
        // 当前图片索引
        currentPicIndex: 0,
        // 是否展示图片预览
        showPreviewImg: false,
        // 是否展示输入框
        showTextarea: false,
        textareaValue: '',
        // 最大字数限制
        max: 100,
        // 触发照片墙刷新
        refresh: false,
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let isSafeBottom = app.globalData.isIpx;
        var that = this;
        //  高度自适应
        wx.getSystemInfo({
            success: function (res) {
                let clientHeight = res.windowHeight,
                    clientWidth = res.windowWidth,
                    rpxR = 750 / clientWidth,
                    scrollViewHeight;
                if (isSafeBottom) {
                    scrollViewHeight = clientHeight * rpxR - 142;
                } else {
                    scrollViewHeight = clientHeight * rpxR - 108;
                }

                that.setData({
                    scrollViewHeight: scrollViewHeight,
                });
            },
        });
        console.log(options.fromWhere);

        let prefix = '';
        if (options.fromWhere == '00') {
            prefix = app.globalData.realname + '·图片墙';
        } else if (options.fromWhere == '01') {
            prefix = app.globalData.addressBack + '·图片墙';
        } else if (options.fromWhere == '02' && options.title && options.id) {
            prefix = `${app.globalData.addressBack}/${options.title}`;
        }

        this.setData({
            prefix: prefix,
            fromWhere: options.fromWhere,
            pointId: options.id,
            pointType: options.pointType,
        });
    },
    onUnload() {},
    // 添加图片
    addImg(e) {
        const that = this;
        wx.chooseImage({
            count: 8 - that.data.sceneImageArr.length,
            success(res) {
                let imgLen =
                    that.data.sceneImageArr.length + res.tempFilePaths.length;
                if (imgLen > 8) {
                    wx.showModal({
                        content: '最多上传8张图片，请重新上传',
                        showCancel: false,
                    });
                    return;
                } else {
                    wx.showLoading({
                        title: '图片上传中',
                        mask: true,
                    });
                    const imgUploadResults = [];
                    let index = that.data.sceneImageArr.length;
                    for (let i = 0; i < res.tempFilePaths.length; i++) {
                        let imgUploadResult = app.imgUpload(
                            res.tempFilePaths[i]
                        );
                        imgUploadResult.then((res) => {
                            let num = i + index;
                            that.data.sceneImageArr[num] = res;
                            that.setData({
                                sceneImageArr: that.data.sceneImageArr,
                            });
                            console.log(that.data.sceneImageArr);
                        });
                        imgUploadResults.push(imgUploadResult);
                    }
                    Promise.all(imgUploadResults).then((values) => {
                        wx.hideLoading();
                    });
                }
            },
        });
    },
    // 删除图片
    deleteImg(e) {
        let index = e.currentTarget.dataset.index;
        console.log(index);
        this.data.sceneImageArr.splice(index, 1);
        // 如果该图片有图片描述也需要删除
        if (this.data.description[index]) {
            this.data.description.splice(index, 1);
        }
        this.setData({
            sceneImageArr: this.data.sceneImageArr,
            description: this.data.description,
        });
    },
    // 预览图片
    previewImgDes(e) {
        let index = e.currentTarget.dataset.index;
        this.setData(
            {
                currentPicIndex: index,
            },
            () => {
                wx.navigateTo({
                    //hideBottom隐藏图片预览的删除按钮
                    url: `../../../pages/checkIn/imgPreview/imgPreview?hideBottom=${true}`,
                });
            }
        );
    },

    addDescription(e) {
        let index = e.currentTarget.dataset.index;
        this.setData(
            {
                currentDesIndex: index,
            },
            () => {
                this.setData({
                    showTextarea: true,
                    textareaValue:
                        this.data.description[this.data.currentDesIndex] || '',
                });
            }
        );
    },

    onBlur(e) {
        this.setData({
            showTextarea: false,
        });
    },

    onInput(e) {
        this.setData({
            textareaValue: e.detail.value,
        });
    },

    submitDescription() {
        this.data.description[
            this.data.currentDesIndex
        ] = this.data.textareaValue;
        this.setData({
            description: this.data.description,
        });
    },

    submit: throttle(function () {
        if (app.visitorPublish()) return; //游客发布限制
        // 处理图片数组为空的情况
        if (this.data.sceneImageArr.length === 0) return;
        let _that = this;
        wx.showLoading({
            title: '图片提交中',
        });
        let photoWalls = [];
        _that.data.sceneImageArr.map((imageUrl, index) => {
            photoWalls.push({
                country: app.globalData.countryBack,
                cityflg: _that.data.fromWhere === '01' ? '00' : '01',
                cityname: app.globalData.addressBack,
                picurl: imageUrl,
                pointflg: _that.data.fromWhere === '02' ? '00' : '01',
                personalflg: '00',
                picdescription: _that.data.description[index] || '',
            });
            if (_that.data.pointId && _that.data.pointType) {
                photoWalls[index].pointid = _that.data.pointId;
                photoWalls[index].pointtype = _that.data.pointType;
            }
        });
        wx.request({
            method: 'POST',
            url:
                app.globalData.rootPath +
                'cjMap/createPhotoWall?authId=' +
                app.globalData.authId,
            data: photoWalls,
            success(res) {
                _that.setData({
                    refresh: true,
                });
                if (res.data.status == '0') {
                    wx.hideLoading();
                    let pages = getCurrentPages(); //当前页面栈
                    let prevPage = pages[pages.length - 2]; //上一页面
                    // prevPage.setData({
                    //     //直接给index页面赋值
                    //     refresh: this.data.refresh
                    // });
                    prevPage.refresh();
                    // 提交完将图片数组长度置为零，防止多次提交
                    _that.data.sceneImageArr.length = 0;
                    wx.showToast({
                        title: '提交成功',
                        icon: 'success',
                        duration: 1500,
                    });
                    setTimeout(function () {
                        wx.navigateBack({
                            delta: 1,
                        });
                    }, 2000);
                }
            },
        });
    }, 10000),
});
